﻿using System.Collections.Generic;
using System.Globalization;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;

namespace NHibernate.Sidekick.Utils.MappingConventions
{
    /// <summary>
    /// Generates a unique Oracle sequence for each identity (primary key),
    /// instead of sharing a single 'hibernate-sequence' across all tables.
    /// Note: This rule only applies to integer value types (int, uint, long, ulong).
    /// </summary>
    public class OraclePrimaryKeySequenceConvention : IIdConvention
    {
        /// <summary>
        /// Apply changes to the target.
        /// </summary>
        /// <param name="instance"></param>
        public void Apply(IIdentityInstance instance)
        {
            if (_validSequenceTypes.Contains(instance.Property.PropertyType.FullName))
            {
                instance.GeneratedBy.Sequence(string.Format(CultureInfo.InvariantCulture,
                                                                "SEQ_{0}", instance.EntityType.Name)); 
            }
        }

        private readonly IList<string> _validSequenceTypes = new List<string>
                                                                 {
                                                                     "System.Int32",
                                                                     "System.UInt32",
                                                                     "System.Int64",
                                                                     "System.UInt64"
                                                                 };
    }
}
